package com.gjp.jooqspringboot.config;

import org.jooq.ConnectionProvider;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.springframework.boot.autoconfigure.jooq.SpringTransactionProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import javax.sql.DataSource;

/**
 * Created by Gjp on 2018/7/25.
 * JOOQ配置文件
 */
@Configuration
public class JooqConfig {

	@Bean
	public DSLContext dslContext(DataSource dataSource){
		//事务织入代理
		TransactionAwareDataSourceProxy proxyTransaction = new TransactionAwareDataSourceProxy(dataSource);
		//数据源连接池，织入事务代理类
		ConnectionProvider connectionProvider =  new DataSourceConnectionProvider(proxyTransaction);
		//事务管理器
		DataSourceTransactionManager txMgr =  new DataSourceTransactionManager(dataSource);
		//配置类
		return DSL.using(
			new DefaultConfiguration()
				.set(connectionProvider)	//数据源连接池提供者
				.set(new SpringTransactionProvider(txMgr))	//spring事务提供者
				.set(SQLDialect.MYSQL)	//数据库方言
		);
	}
}
